import random
import string

from flask import Blueprint, render_template, jsonify, redirect, url_for, session
from models import Usermodel
from blue_print.forms import RegisterForm, LoginForm
from exts import mail,db
from flask_mail import Message
from flask import request
from models import EmailCaptureModel

bp = Blueprint('auth', __name__,url_prefix="/auth")


@bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template("login.html")
    else:
        form = LoginForm(request.form)
        # 自己写的
        # if form.validate():
        #     email = form.email.data
        #     password = form.password.data
        #     email_user = Usermodel.query.filter_by(email=email).first()
        #     password_user = Usermodel.query.filter_by(password=password).first()
        #     print(email_user)
        #     print(password_user)
        #     if email_user and password_user:
        #         return redirect(url_for('auth.register'))
        #     else:
        #         print(form.errors)
        #         return redirect(url_for('auth.login'))
        # 教程
        if form.validate():
            email = form.email.data
            password = form.password.data
            user = Usermodel.query.filter_by(email=email).first()
            if not user:
                return redirect(url_for("auth.login"))
            if user.password == password:
                session['user_id'] = user.id
                return redirect("/")
            else:
                return redirect(url_for("auth.login"))
        else:
            print(form.errors)
            return redirect(url_for("auth.login"))


# get :从服务器上面获取数据
# post:将客户端的数据提交给服务器
@bp.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == "GET":
        return render_template("register.html")
    else :
        # 验证用户提交的验证码是否正确
        # 表单验证：flask-wtf:wtform
        form = RegisterForm(request.form)
        if form.validate():
            username = form.username.data
            email = form.email.data
            password = form.password.data
            user = Usermodel(username=username, email=email, password=password)
            db.session.add(user)
            db.session.commit()
            return redirect("/auth/login")
        else:
            print(form.errors)
            return redirect(url_for("auth.register"))


# 没有指定route的methods的参数，默认是get请求
@bp.route('/capture/email')
def capture_email():
    email = request.args.get("email")
    source = string.digits
    capture = random.sample(source,4)
    capture = "".join(capture)
    message = Message(subject="登录验证码", recipients=[email], body=capture)
    mail.send(message)
    #memcached/redis是将数据存储在缓存中
    #我们本次用数据库的方式存储验证码
    email_capture = EmailCaptureModel(email=email, capture=capture)
    db.session.add(email_capture)
    db.session.commit()
    return jsonify({"code": 200, "message": "", "data": None})

@bp.route('/logout')
def logout():
    # 清除浏览器上的用户登录信息
    session.clear()
    return redirect(url_for("auth.login"))


@bp.route('/mail/test')
def mail_test():
    message = Message(subject="邮箱测试",recipients=["502701428@qq.com"],body="这是一条测试邮件！")
    mail.send(message)
    return "邮件发送成功！"
